package com.gradecak.alfresco.mvc.converter;

import java.io.IOException;

import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.namespace.QName;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;
import org.springframework.util.StringUtils;

public class QnameDeserializer extends JsonDeserializer<QName> {

  private ServiceRegistry serviceRegistry;

  public QnameDeserializer(ServiceRegistry serviceRegistry) {
    this.serviceRegistry = serviceRegistry;
  }

  @Override
  public QName deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {

    String qname = jp.getText();
    if (StringUtils.hasText(qname)) {
      return QName.createQName(qname, serviceRegistry.getNamespaceService());
    }

    throw ctxt.mappingException("Expected a valid QName string representation");
  }

}
